<?php
class Pageley_Gateway_Database_LargeObject extends Pageley_Domain_BasicEntity {
	
    private $data;
    private $location;
    
    public function __construct() {
        parent::__construct(self::type());
	}

	public static function type() {
		$factory = Pageley_Config::getInstance();
		return $factory->valueOf("type.system.LargeObject");
	}
    
	public function getReader() {
        $reader = $this->get("data");
        $reader->reset();
        return $reader;
    }
    
    public function getData() {
        if($this->data === null) {
            $this->data = $this->getReader()->readAll();
        }
        return $this->data;
    }
    
    public function getMimeType() {
        return $this->get("mimeType");
    }
    
    public function getLocation() {
    	if($this->location === null) {
            $pathManager = Pageley_Util_PathManager::getInstance();
            $relativePath = $this->getType()->getNamespace()->getAlias() . "/" . $this->getType()->getName() . "/" . $this->getId();
            $filePath = $pathManager->getFilePath("largeObjectCache");
            $contextPath = $pathManager->getContextPath("largeObjectCache");
            $this->location = $contextPath . $relativePath;
            $this->cache($filePath . $relativePath);
        }
        return $this->location;
    }
    
    private function cache($location) {
        $file = new Pageley_Util_File($location);
        if(!$file->exists()) {
            $writer = new Pageley_Util_FileWriter($file);
            $writer->stream($this->getReader());
            $writer->close();
        }
    }
	
}